package cn.com.connext.scrm.task;

import cn.com.connext.scrm.domain.master.ZnhjEntity;
import cn.com.connext.scrm.domain.master.ZnhjEntityTemp;
import cn.com.connext.scrm.repository.master.ZnhjEntityTempRepository;
import cn.com.connext.scrm.repository.master.ZnhjRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RestController
public class ZnhjEntityTask {
    private final Logger log = LoggerFactory.getLogger(ZnhjEntityTask.class);

    @Autowired
    private ZnhjEntityTempRepository znhjEntityTempRepository;
    @Autowired
    private ZnhjRepository znhjRepository;

    /**
     *
     */
    //每十分钟执行一次
    @Scheduled(cron = "0 0/10 * * * ?")
    @PostMapping("/znhjEntityHandle")
    @Transactional
    public void znhjEntityHandle() {
        log.info("处理znhjEntityTemp数据定时任务start");
        this.activationListHandle();
        this.cancelListHandle();
        log.info("处理znhjEntityTemp数据定时任务end");
    }

    public void activationListHandle() {
        log.info("处理znhjEntityTemp激活数据start");
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //查询激活类型数据
        Specification<ZnhjEntityTemp> activationSpecification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("operation"), 1));
            list.add(criteriaBuilder.equal(root.get("status"), "00"));
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<ZnhjEntityTemp> activationList = znhjEntityTempRepository.findAll(activationSpecification, sort);
        if (!CollectionUtils.isEmpty(activationList)) {
            Iterator<ZnhjEntityTemp> it = activationList.iterator();
            //不符合条件的数据记录下来操作完成后更新为 20状态
            List<String> ids = new ArrayList<>();
            while (it.hasNext()) {
                ZnhjEntityTemp item = it.next();
                if (StringUtils.isEmpty(item.getBottleCode()) || StringUtils.isEmpty(item.getReelCode())
                    || StringUtils.isEmpty(item.getBatchNo()) || StringUtils.isEmpty(item.getSkuId())
                    || StringUtils.isEmpty(item.getUniqueCode())) {
                    ids.add(item.getId());
                    it.remove();
                    continue;
                }
            }
            //更新不符合条件的temp数据status
            if (!CollectionUtils.isEmpty(ids)) {
                znhjEntityTempRepository.batchUpdate(ids, "20");
            }

            if (!CollectionUtils.isEmpty(activationList)) {
                //获取activationList内所有bottleUnique集合
                List<String> bottleUniqueList = activationList.stream().map(ZnhjEntityTemp::getBottleUnique).collect(Collectors.toList());
                List<String> rightIds = activationList.stream().map(ZnhjEntityTemp::getId).collect(Collectors.toList());
                //activationList赋值给entityList
                List<ZnhjEntity> entityList = activationList.stream().map(activation -> {
                    ZnhjEntity znhj = new ZnhjEntity();
                    BeanUtils.copyProperties(activation, znhj);
                    return znhj;
                }).collect(Collectors.toList());
                List<ZnhjEntity> all = znhjRepository.findByCondition(bottleUniqueList);

                entityList.removeAll(all);
                if (entityList.size() > 0) {
                    for (ZnhjEntity entity1 : entityList) {
                        entity1.setCreateTime(ZonedDateTime.now());
                        entity1.setIsActivity(2);
                        entity1.setStatus(1);
                        entity1.setIsScan(2);//是否被扫描 1是 2否
                    }
                }
                znhjRepository.save(entityList);
                log.info("处理znhjEntityTemp激活数据条数：" + entityList.size());
                //更新符合条件的tempstatus
                znhjEntityTempRepository.batchUpdate(rightIds, "10");
            }

        }
        log.info("处理znhjEntityTemp激活数据end");
    }

    public void cancelListHandle() {
        log.info("处理znhjEntityTemp作废数据start");
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //查询作废类型数据
        Specification<ZnhjEntityTemp> cancelSpecification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("operation"), 2));
            list.add(criteriaBuilder.equal(root.get("status"), "00"));
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<ZnhjEntityTemp> cancelList = znhjEntityTempRepository.findAll(cancelSpecification, sort);
        if (!CollectionUtils.isEmpty(cancelList)) {
            List<String> collect = cancelList.stream().map(ZnhjEntityTemp::getBottleCode).collect(Collectors.toList());
            //记录id更新temp表status
            List<String> ids = cancelList.stream().map(ZnhjEntityTemp::getId).collect(Collectors.toList());
            znhjRepository.batchUpdate(collect);
            log.info("处理znhjEntityTemp作废数据条数：" + collect.size());
            //更新temp表status
            znhjEntityTempRepository.batchUpdate(ids, "10");
        }
        log.info("处理znhjEntityTemp作废数据end");
    }
}
